package com.dunghn.loadtest;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vg.com.chatonline.activity.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import ce51.dunghn.imagethread.ExtendedImageDownloader;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class ScrollLoadContact extends BaseActivity {
	private int currentPage = 0;
	private int previousTotal = 0;
	private boolean loading = true;
	ArrayList<HashMap<String, String>> contact;
	ContactAdapter adapter;
	DisplayImageOptions options;
	ListView lv;
	LinearLayout layout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc()
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		ListView lv = (ListView) findViewById(R.id.contact_lvContact);
		
		View footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.listfooter, null, false);
		lv.addFooterView(footerView);
		contact = new ArrayList<HashMap<String, String>>();
		adapter = new ContactAdapter(this, contact);
		lv.setAdapter(adapter);
		lv.setOnScrollListener(new OnScrollListener() {

			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (loading) {
					if (totalItemCount > previousTotal) {
						loading = false;
						previousTotal = totalItemCount;
						currentPage++;
					}
				}
				if (!loading
						&& (totalItemCount == (firstVisibleItem + visibleItemCount))) {
					new LoadContactTask().execute(currentPage);
					loading = true;
				}
			}
		});
	}

	private class LoadContactTask extends
			AsyncTask<Integer, Void, ArrayList<HashMap<String, String>>> {

		@Override
		protected ArrayList<HashMap<String, String>> doInBackground(
				Integer... t) {
			ArrayList<HashMap<String, String>> arr = new ArrayList<HashMap<String, String>>();
			try {
				arr.addAll(loadContactData(t[0]));
			} catch (Exception e) {
				Log.d("AsyncTask ", e.toString());
			}
			return arr;
		}

		@Override
		protected void onPostExecute(ArrayList<HashMap<String, String>> arr) {
			contact.addAll(arr);
			adapter.notifyDataSetChanged();
		}
	}

	public ArrayList<HashMap<String, String>> loadContactData(int mPage) {
		ArrayList<HashMap<String, String>> contact_list = new ArrayList<HashMap<String, String>>();
		JSONArray data = new JSONArray();
		JsonParse js = new JsonParse();
		JSONObject jso = new JSONObject();
		jso = js.getJSONFromUrl("http://deduocyeu.com/json/getUserStatus.php?page="
				+ mPage + "&pagesize=10");
		try {
			data = jso.getJSONArray("data");
			for (int i = 0; i < data.length(); i++) {
				JSONObject obj = data.getJSONObject(i);
				String name = obj.getString("use_fullname");
				String image = obj.getString("use_avatar");
				HashMap<String, String> arr = new HashMap<String, String>();
				arr.put("use_fullname", name);
				arr.put("use_avatar", image);

				contact_list.add(arr);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return contact_list;
	}

	public class ContactAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		Context c;
		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

		public ContactAdapter(Context context,
				ArrayList<HashMap<String, String>> d) {
			c = context;
			data = d;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return data.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View vi = convertView;
			if (convertView == null) {
				inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				vi = inflater.inflate(R.layout.custom_lv_contact, null);
			}
			TextView txtView = (TextView) vi
					.findViewById(R.id.contact_txt_name);
			ImageView imageView = (ImageView) vi
					.findViewById(R.id.contact_img_avatar);
			layout=(LinearLayout)vi.findViewById(R.id.layout_param);
			int screenWidth = getApplicationContext().getResources().getDisplayMetrics().widthPixels;
			LinearLayout.LayoutParams ll_params = new LinearLayout.LayoutParams(screenWidth, screenWidth/6);
			layout.setLayoutParams(ll_params);

			txtView.setText(data.get(position).get("use_fullname"));
			ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
					getApplicationContext())
					.threadPriority(Thread.NORM_PRIORITY - 2)
					.memoryCacheSize(2 * 1024 * 1024)
					.denyCacheImageMultipleSizesInMemory()
					.discCacheFileNameGenerator(new Md5FileNameGenerator())
					.imageDownloader(
							new ExtendedImageDownloader(getApplicationContext()))
					.tasksProcessingOrder(QueueProcessingType.LIFO)
					.enableLogging().build();
			ImageLoader.getInstance().init(config);
			imageLoader.displayImage(data.get(position).get("use_avatar"),
					imageView, options);

			return vi;
		}
	}
}
